/**
 * @Author: easten
 * @Created: 2024-04-15 23:29:48
 * @Description:
 *
 */
import classnames from "classnames";
// import { clearPageState, getList, selectListBase } from 'modules/list/base';
// import { useAppDispatch, useAppSelector } from 'modules/store';
import React, { useState, useEffect, useMemo } from "react";
import {
  FileDownloadIcon,
  HomeIcon,
  LogoCodepenIcon,
  RefreshIcon,
} from "tdesign-icons-react";
import {
  Button,
  Popconfirm,
  Space,
  Table,
  Tag,
  Tooltip,
  Tree,
  Upload,
  message,
} from "tdesign-react";
// const ExcelJS = require('exceljs/dist/es5');
import ExcelJS from "exceljs";
import { ModuleCommonProps, PageParams, TreeDataModel } from "_common/DataType";
import { IotPoint } from "_common/entity";
import { ApiFacility } from "_common/api/iot/ApiFacility";
import { ApiPoint } from "_common/api/iot/ApiPoint";
import TableTitle from "components/common/TableTitle";
import PointDrawer from "./PointDrawer";
export type IotPointCompProps = ModuleCommonProps & {};
const IotPointComp: React.FC<IotPointCompProps> = (
  props: IotPointCompProps
) => {
  const { axios, className } = props;
  const [selectedRowKeys, setSelectedRowKeys] = useState<(string | number)[]>(
    []
  );
  const [loading, setLoading] = useState<boolean>(false);
  const [pointList, setPointList] = useState<IotPoint[]>([]);
  const [selectedRow, setSelectedRow] = useState<IotPoint>();
  const [visible, setVisible] = useState(false);
  const [edit, setEdit] = useState(false);
  const [terminalTree, setWorkshopTree] = useState<TreeDataModel[]>([]);
  const [selectNode, setSelectNode] = useState<TreeDataModel | undefined>();
  const [files, setFiles] = useState<File[]>([]);
  const [pageState, setPageState] = useState<PageParams>({
    pageNum: 1,
    pageSize: 10,
    total: 0,
    list: [],
  });

  const apiFacility = new ApiFacility(axios);
  const apiPoint = new ApiPoint(axios);

  function onSelectChange(value: (string | number)[]) {
    setSelectedRowKeys(value);
  }

  useEffect(() => {
    getTree();
  }, []);

  // 查询监测点
  const getPointList = async () => {
    setSelectedRowKeys([]);
    const response = await apiPoint.getPage({
      pageNum: pageState.pageNum,
      pageSize: pageState.pageSize,
      id: selectNode?.value,
    });
    if (response && response.code == 200 && response.data) {
      setPointList(response.data.list);
      setPageState({
        ...pageState,
        total: response.data.total,
      });
    } else {
      setPointList([]);
    }
  };

  useEffect(() => {
    getPointList();
  }, [selectNode, pageState.pageNum, pageState.pageSize]);

  // 删除
  const deleteMonitor = async (id: number) => {
    const response = await apiPoint.delete(id);
    if (response && response.code == 200) {
      message.success("删除成功");
      getPointList();
    }
  };

  // 批量删除
  const deleteBatchMonitor = async () => {
    const response = await apiPoint.batchDelete(selectedRowKeys);
    if (response && response.code == 200) {
      message.success("删除成功");
      getPointList();
    }
  };

  // 获取结构树
  const getTree = async () => {
    const response = await apiFacility.getTree();
    if (response && response.code == 200) {
      setWorkshopTree(response.data);
    }
  };

  // 导出模板
  const exportExcelTemp = () => {
    const workbook = new ExcelJS.Workbook();
    const sheet = workbook.addWorksheet("Sheet");
    sheet.columns = [
      { header: "测点名称", key: "name", width: 10 },
      { header: "测点编码", key: "code", width: 30 },
      {
        header: "测点类型（与数据字典中类型需要对应）",
        key: "deviceName",
        width: 40,
      },
      { header: "设备ID", key: "deviceCode", width: 20 },
      { header: "测点位置", key: "deviceCode", width: 20 },
    ];
    workbook.xlsx.writeBuffer().then((buffer) => {
      writeFile("监测点导入模板", buffer);
    });
  };

  const writeFile = (fileName: string, content: any) => {
    const link = document.createElement("a");
    const blob = new Blob([content], {
      type: "application/vnd.ms-excel;charset=utf-8;",
    });
    link.download = fileName;
    link.href = URL.createObjectURL(blob);
    link.click();
  };

  const renderLabel = (node: any) => {
    let data = node.data;
    if (data.type == 1) {
      return (
        <Tag
          theme="warning"
          variant="outline"
          icon={<HomeIcon color="#EF9735" />}
          size="small"
        >
          站点：{data.label}
        </Tag>
      );
    } else {
      return (
        <Tag
          theme="success"
          variant="outline"
          icon={<LogoCodepenIcon color="#1AA84F" />}
          size="small"
        >
          设施： {data.label}
        </Tag>
      );
    }
  };

  const treeNode = useMemo(() => {
    return (
      <Tree
        data={terminalTree}
        activable
        hover
        transition
        label={renderLabel}
        className="ml-0"
        onActive={(e, c) => {
          if (e.length == 0) {
            setSelectNode(undefined);
          } else {
            setSelectNode(c.node.data as any);
          }
        }}
      />
    );
  }, [terminalTree, selectNode]);

  return (
    <div className={classnames(className, "flex", "flex-row h-full")}>
      <div
        style={{
          width: 300,
          borderRight: "1px solid var(--td-border-level-1-color)",
        }}
        className="h-full"
      >
        <TableTitle text="设施信息" />
        <div className="pt-4 pr-5 pl-0">{treeNode}</div>
      </div>
      <div
        className={classnames("pl-5")}
        style={{ width: "calc(100% - 300px)" }}
      >
        <div className="flex flex-row justify-between mb-4">
          <TableTitle text="测点列表" />
          <Space size={5}>
            {selectedRowKeys.length > 0 && (
              <Popconfirm
                content="确认删除吗"
                destroyOnClose
                placement="top"
                showArrow
                theme="default"
                onConfirm={() => deleteBatchMonitor()}
              >
                <Button theme="danger" variant="outline">
                  批量删除({selectedRowKeys.length})
                </Button>
              </Popconfirm>
            )}
            <Button
              onClick={() => {
                // 判断是否选择了
                if (!selectNode || selectNode.type == 1) {
                  message.error("请选择设施");
                  return;
                }
                setVisible(true);
                setEdit(false);
              }}
            >
              添加测点
            </Button>
            <Upload
              files={files}
              onChange={(files) => {
                setFiles(files);
              }}
              theme="custom"
              beforeUpload={async (file) => {
                // 提交到后台
                // file 转换为 IFormFile
                if (file == null) return false;
                var formData = new FormData();
                // @ts-ignore
                formData.append("file", file.raw);
                const response = await apiPoint.import(
                  selectNode?.value!,
                  formData
                );
                if (response && response.code == 200 && response.data) {
                  message.success("上传成功");
                  getPointList();
                }
                return true;
              }}
              accept=".xls,.xlsx"
            >
              <Button
                theme="primary"
                onClick={(e) => {
                  if (!selectNode || selectNode.type == 1) {
                    message.error("请选择车间");
                    e.stopPropagation();
                    return;
                  }
                }}
              >
                批量上传
              </Button>
            </Upload>
            <Tooltip content="下载模板">
              <Button
                icon={<FileDownloadIcon />}
                variant="outline"
                onClick={() => {
                  // 下载模板
                  exportExcelTemp();
                }}
              ></Button>
            </Tooltip>
            <Button
              icon={<RefreshIcon />}
              variant="outline"
              onClick={() => {
                getPointList();
              }}
            ></Button>
          </Space>
        </div>

        <Table<IotPoint>
          bordered
          columns={[
            {
              colKey: "row-select",
              type: "multiple",
              width: 50,
            },
            {
              align: "left",
              width: 120,
              ellipsis: true,
              colKey: "index",
              title: "序号",
              cell: ({ rowIndex }) => {
                let _index =
                  (pageState.pageNum - 1) * pageState.pageSize + rowIndex + 1;
                return <span>{_index}</span>;
              },
            },
            {
              align: "left",
              ellipsis: true,
              colKey: "name",
              title: "测点名称",
            },
            {
              align: "left",
              ellipsis: true,
              colKey: "code",
              title: "测点编码",
            },
            {
              align: "center",
              ellipsis: true,
              colKey: "location",
              title: "安装位置",
            },
            {
              align: "center",
              ellipsis: true,
              colKey: "device1",
              title: "关联设备ID",
              cell({ row }) {
                return (
                  <Tag color="#1B8DE0" variant="light-outline">
                    {row.device?.deviceCode ?? "未绑定设备"}
                  </Tag>
                );
              },
            },
            {
              align: "center",
              ellipsis: true,
              colKey: "deviceType.",
              title: "设备类型",
              cell({ row }) {
                return (
                  <Tag theme="primary" variant="light-outline">
                    {row.device?.group?.groupName}
                  </Tag>
                );
              },
            },
            {
              align: "center",
              fixed: "right",
              width: 220,
              colKey: "op",
              title: "操作",
              cell({ row }) {
                return (
                  <>
                    <Button
                      theme="success"
                      variant="text"
                      onClick={() => {
                        setVisible(true);
                        setEdit(true);
                        setSelectedRow(row);
                      }}
                    >
                      编辑
                    </Button>
                    <Popconfirm
                      content="确认删除吗"
                      destroyOnClose
                      placement="top"
                      showArrow
                      theme="default"
                      onConfirm={() => deleteMonitor(row.id!)}
                    >
                      <Button theme="primary" variant="text">
                        删除
                      </Button>
                    </Popconfirm>
                  </>
                );
              },
            },
          ]}
          loading={loading}
          data={pointList}
          rowKey="id"
          selectedRowKeys={selectedRowKeys}
          verticalAlign="middle"
          hover
          onSelectChange={onSelectChange}
          pagination={{
            pageSize: pageState.pageSize,
            total: pageState.total,
            current: pageState.pageNum,
            showJumper: true,
            onCurrentChange(current) {
              setPageState({
                ...pageState,
                pageNum: current,
              });
            },
            onPageSizeChange(size) {
              setPageState({
                ...pageState,
                pageSize: size,
              });
            },
          }}
        />
      </div>
      <PointDrawer
        open={visible}
        axios={axios}
        edit={edit}
        facility={selectNode}
        value={selectedRow}
        onSuccess={() => {
          setVisible(false);
          getPointList();
        }}
      />
    </div>
  );
};
export default IotPointComp;
